/**
 *    Copyright 2006-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.mybatis.generator.plugins.custome;

import org.apache.log4j.Logger;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Set;

public class StringUtil {

    private static final Logger LOGGER = Logger.getLogger(StringUtil.class);

    static String DEFAULT_CHARSET = "UTF-8";

    static String EMPTY_STR = "";

    public static boolean isNotEmpty(String s) {
        return s != null && !s.equals("");

    }

    public static String excludeNull(final String str) {
        if (isNotEmptyOrNull(str)) {
            return str;
        }
        return "";
    }

    /**
     * 判断是否为空或者'null'字符串.
     *
     * @param s
     * @return
     */
    public static boolean isNotEmptyOrNull(String s) {
        if (isNotEmpty(s)) {
            return !"null".equals(s);
        }
        return false;
    }

    public static int parseInt(final String numStr) {
        if (isNotEmpty(numStr)) {
            try {
                return Integer.parseInt(numStr);
            } catch (NumberFormatException e) {
                LOGGER.error("Parse int error,numStr is " + numStr, e);
            }
        }
        return 0;
    }

    public static boolean isNotEmpty(Object s) {
        return s != null && !s.toString().equals("");
    }

    public static boolean isEmptyOr0(Object s) {
        return s == null || s.toString().equals("") || s.toString().equals("0");
    }

    public static boolean checkMail(String s) {
        if (!isNotEmpty(s))
            return false;
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        return s.matches(EMAIL_REGEX);

    }

    public static boolean checkPhone(String s) {
        if (!isNotEmpty(s))
            return false;
        // String regExp = "^[1](((33|53|80|89)[0-9]{8})|(349[0-9]{7}))$";
        // String regExp =
        // "^0?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
        String regExp = "^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
        return s.matches(regExp);

    }

    public static Long getPageCount(Long total, Long pageSize) {
        if (total % pageSize == 0) {
            return total / pageSize;
        } else {
            return total / pageSize + 1;
        }
    }

    /**
     * 功能描述：输入参数为秒
     *
     * @param intervalTime
     * @return String
     */
    public static String getIntervalUpdateTime(long intervalTime) {
        StringBuilder result = new StringBuilder();
        long interval = intervalTime;
        final long day = 24 * 60 * 60;
        final long hour = 60 * 60;
        final long minute = 60;
        int detailDay = 0;
        int detailHour = 0;
        int detailMinute = 0;
        // int detailSecond = 0;
        if (interval >= day) {
            detailDay = (int) (interval / day);
            interval = interval - detailDay * day;
        }
        if (interval >= hour) {
            detailHour = (int) (interval / hour);
            interval = interval - hour * detailHour;
        }
        if (interval >= minute) {
            detailMinute = (int) (interval / minute);
            interval = interval - detailMinute * minute;
        }
        // if (interval > 0) {
        // detailSecond = (int) interval;
        // }
        result.setLength(0);
        if (detailDay > 0) {
            result.append(detailDay);
            result.append("天前");
            // result.append(":");
        } else if (detailHour > 0) {
            result.append(detailHour);
            result.append("小时前");
        } else if (detailMinute > 0) {
            // if (detailHour > 0)
            // result.append(":");

            result.append(detailMinute);
            result.append("分钟前");
        } else {
            result.append("刚刚");
        }
        // if (detailSecond > 0) {
        // result.append(":");
        // if (detailSecond < 10)
        // result.append("0" + detailSecond);
        // else
        // result.append(detailSecond);
        //
        // } else {
        // result.append(":00");
        // }
        return result.toString();
    }

    public static String getPlayCount(Long c) {
        // 1、0-9999之间，直接显示数字，不带任何单位；
        // 2、大于10000，除以10000，保留一位小数（无需四舍五入），显示x.x万（带上单位万），小数位是0，就直接去掉小数位
        // 3.大于等于1亿，显示1.1亿，保留一位小数
        // 例如：10000--1万 10001--1万 11000--1.1万 115000--1.1万
        if (c == null)
            return "0";
        String out = "";

        if (c < 10000) {
            out = c + "";
        } else if (c >= 100000000) {
            Long x = c % 100000000;
            if (x >= 10000000) {
                out = c / 100000000 + "." + x / 10000000 + "亿";
            } else {
                out = c / 100000000 + "亿";
            }
        } else {
            Long yu = c % 10000;
            if (yu >= 1000) {
                out = c / 10000 + "." + yu / 1000 + "万";
            } else {
                out = c / 10000 + "万";
            }
        }
        return out;
    }

    public static String urlEncodeUtf8(final String encodeStr) {
        if (!isNotEmpty(encodeStr)) {
            return encodeStr;
        }
        try {
            return URLEncoder.encode(encodeStr, DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("UrlEncode utf-8 error " + encodeStr, e);
        }
        return encodeStr;
    }

    //数字转中文
    static String[] units = {"", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "万亿"};
    static char[] numArray = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};

    @SuppressWarnings("unused") public static String foematInteger(int num) {
        char[] val = String.valueOf(num).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String m = val[i] + "";
            int n = Integer.valueOf(m);
            boolean isZero = n == 0;
            String unit = units[(len - 1) - i];
            if (isZero) {
                if ('0' == val[i - 1]) {
                    // not need process if the last digital bits is 0
                    continue;
                } else {
                    // no unit for 0
                    sb.append(numArray[n]);
                }
            } else {
                sb.append(numArray[n]);
                sb.append(unit);
            }
        }
        return sb.toString();
    }

    /**
     * 批量替换,原字符串为空时返回""
     *
     * @param str
     * @param ori
     * @param replace
     * @return
     */
    public static String replaceReExcludeNull(final String str, final String ori,
                                              final String replace) {
        if (StringUtil.isNotEmpty(str)) {
            return str.replaceAll(ori, replace);
        }
        return "";
    }

    /**
     * 将\r\n 转成xml 格式
     *
     * @param str
     * @return
     */
    public static String replaceRnToXml(String str) {
        //    	 String rn="</w:t></w:r></w:p><w:p><w:pPr><w:autoSpaceDE w:val=\"0\"/><w:rPr>"
        //        		 + "<w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/>" + " <w:bCs/>" + "<w:sz w:val=\"24\"/>"
        //        		 + "</w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii=\"仿宋\" w:eastAsia=\"仿宋\" w:hAnsi=\"仿宋\" w:hint=\"eastAsia\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/></w:rPr><w:t>";
        String rn = "\r";
        return StringUtil.replaceReExcludeNull(str, "\r\n", rn);

    }

    /**
     * 将str转换为rtf值
     *
     * @param content
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String strToRtf(String content) throws UnsupportedEncodingException {

        StringBuffer sb = new StringBuffer("");
        try {
            char[] digital = "0123456789ABCDEF".toCharArray();
            byte[] bs = null;
            bs = content.getBytes("GB2312");
            int bit;
            for (int i = 0; i < bs.length; i++) {
                bit = (bs[i] & 0x0f0) >> 4;
                sb.append("\\'");
                sb.append(digital[bit]);
                bit = bs[i] & 0x0f;
                sb.append(digital[bit]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static boolean matchBySet(final String target, final Set<String> temps) {
        if (temps == null && temps.size() == 0) {
            return true;
        }
        PathMatcher matcher = new AntPathMatcher();
        for (String path : temps) {
            if (matcher.match(path, target)) {
                return true;
            }
        }
        return false;
    }
    public static String isoToChar(String str, String charset)
    {
    	String caseString = "";
    	try {
		caseString = new String(str.getBytes("iso-8859-1"), charset);
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("Parse error is",e);
			
		}    	
		return caseString;   	   	    	
    }

    public static void main(String[] args) {
        // String s = "1231@163.com";
        // boolean b = checkMail(s);
        // System.out.println(b);
        // String s;
        // try {
        // s = URLEncoder.encode("百事通", "utf-8");
        // System.out.println(s);
        // String ss = URLDecoder.decode(s, "utf-8");
        // System.out.println(ss);
        // } catch (UnsupportedEncodingException e) {
        // e.printStackTrace();
        //
        // }
        // String s = StringUtil.getIntervalUpdateTime(30L);
        // boolean b = StringUtil.checkPhone("13481111112");
        // System.out.println(b);
        // String s = "113_token_34343";
        // System.out.println(s.substring(0, s.indexOf("_token")));
        // Long c = 201000000L;
        // String s = StringUtil.getPlayCount(c);
        Long c = 0L;
        boolean b = StringUtil.isEmptyOr0(c);
        System.out.println(b);
    }
    
    
}
